package com.csnf.Dao;

import com.csnf.entity.UserAuthors;
import com.csnf.entity.UserBooks;
import com.csnf.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BooksDao {

    public List<UserBooks> getAllBooksByName(String bookName) throws Exception {
        List<UserBooks> bookList = new ArrayList<>();
        Connection conn = JdbcUtil.getConnection();
        String sql = "select * from books where book_name like concat('%',?,'%')";
        PreparedStatement ps = JdbcUtil.getPreparedStatement(conn,sql,bookName);
        ps.setString(1, bookName);
        ResultSet rs = ps.executeQuery();
        while (rs.next()){
            UserBooks books=JdbcUtil.invokeObject(rs,UserBooks.class);
            String sql1 = "select * from authors where author_id=?";
            PreparedStatement ps1 = JdbcUtil.getPreparedStatement(conn,sql1,books.getAuthor_id());
            ResultSet rs1 = ps1.executeQuery();
            while (rs1.next()){
                UserAuthors authors = JdbcUtil.invokeObject(rs1,UserAuthors.class);
                books.setUserAuthors(authors);
            }
            bookList.add(books);
            JdbcUtil.close(rs1,ps1);
        }
        JdbcUtil.close(rs,ps,conn);
        return bookList;
    }
}
